<?php

namespace App\Http\Controllers\Recharge;

use function app;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderWx;
use function mt_rand;
use function time;

class ServerController extends Controller{


    public function pay($sn, $open_id, $pay_price) {
        return $this->createWechatPay([
            'order_id' => $sn,
            'total_fee' => $pay_price,
            'open_id' => $open_id,
        ]);
    }

    public function createWechatPay(array $params) {
        $notice_url = 'http://r.ddjuly.com/server/wxcallback';
        $body = [
            'body' => '手机充值',
            'out_trade_no' => $params['order_id'],
            'total_fee' => (int)$params['total_fee'],
            'spbill_create_ip' => $this->get_client_ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $notice_url, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $params['open_id'],
        ];

        $app = app("easyWechat");
        $result = $app->order->unify($body);

        // 保存统一下单
        $this->saveOrderWx($params['order_id'], $result);

        $jssdk = $app->jssdk->sdkConfig($result['prepay_id']);

        return $jssdk;
    }


    private function get_client_ip() {
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')) {

            $ip = getenv('HTTP_CLIENT_IP');

        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')) {

            $ip = getenv('HTTP_X_FORWARDED_FOR');

        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'),'unknown')) {

            $ip = getenv('REMOTE_ADDR');

        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {

            $ip = $_SERVER['REMOTE_ADDR'];

        }

        return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    }


    private function saveOrderWx($order_id, $data) {
        try {
            $orderwx = new OrderWx;
            $orderwx->order_id = $order_id;
            $orderwx->prepay_id = $data['prepay_id'];
            $orderwx->status = 1;
            $orderwx->return_code = $data['return_code'];
            $orderwx->return_msg = $data['return_msg'];
            $orderwx->appid = $data['appid'];
            $orderwx->mch_id = $data['mch_id'];
            $orderwx->nonce_str = $data['nonce_str'];
            $orderwx->sign = $data['sign'];
            $orderwx->result_code = $data['result_code'];
            $orderwx->trade_type = $data['trade_type'];
            $orderwx->save();
        } catch (\Exception $e) {

        }
    }

}
